/**
 * 
 */
package com.yullage.ae.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.bytecode.opencsv.CSVWriter;

import com.yullage.ae.core.Mind;
import com.yullage.ae.core.Zone;

/**
 * @author Yu-chun Huang
 * 
 */
public class MindRecorder {
	/**
	 * Logger
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(MindRecorder.class);

	Mind mind;
	List<List<String>> recordList;

	public MindRecorder(Mind mind) {
		if (mind == null) {
			logger.error("Mind can not be null.");
			throw new IllegalArgumentException();
		}

		this.mind = mind;
	}

	public Mind getMind() {
		return mind;
	}

	public void displayText(OutputStream outputStream) throws IOException {
		Writer writer = new OutputStreamWriter(outputStream);
		writer.write("[ Think Time: " + mind.getCurThinkTime() + " ]\n");

		for (Map.Entry<String, Zone> entry : mind.getZonePool().entrySet()) {
			String zoneName = entry.getKey();
			Zone zone = entry.getValue();

			writer.write(String.format("%15s", zoneName) + "  "
					+ zone.getIntensity() + "\n");
		}

		writer.write("\n");
		writer.flush();
	}

	public void displayGraph(Mind mind) {
		// TODO Draw graph
	}

	public void resetRecords() {
		recordList = new ArrayList<List<String>>();
	}

	public void record() {
		List<String> intensities = new ArrayList<String>();

		intensities.add(Long.toString(mind.getCurThinkTime()));
		for (Map.Entry<String, Zone> entry : mind.getZonePool().entrySet()) {
			Zone zone = entry.getValue();
			intensities.add(Double.toString(zone.getIntensity()));
		}

		recordList.add(intensities);
	}

	public void writeRecords(String fileName) throws IOException {
		File outputFolder = new File("mind_output");
		if (!outputFolder.isDirectory()) {
			outputFolder.mkdir();
		}

		CSVWriter writer = new CSVWriter(new FileWriter(fileName));
		String[] entries = new String[mind.getZonePool().size() + 1];

		// Column header
		int i = 1;
		entries[0] = "_ThinkTime";
		for (String zoneName : mind.getZonePool().keySet()) {
			entries[i] = zoneName;
			i++;
		}
		writer.writeNext(entries);

		// Intensity
		for (List<String> row : recordList) {
			i = 0;
			for (String intensity : row) {
				entries[i] = intensity.toString();
				i++;
			}
			writer.writeNext(entries);
		}

		writer.close();
	}
}
